import React, { Component } from "react";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Card, Button, Icon, Input, message, Tag, Upload } from "antd";
import { formatMessage } from 'umi-plugin-react/locale';
import MarkdownEditor from "@/utils/vditor";
import RelatedKnowledgeTag from "@/utils/RelatedKnowledgeTag";
import { addFile, editFile, getFileInfo, docUploadAttach } from "@/services/knowledgeFile";

let timer;
class AddMarkdown extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isShowTitle: false,
			content: '',
			title: '',
			fileTitle: '',
			btnLoading: false,
			knowledgeTagList: [],
			relatedTagVisible: false,
			pageHeight: 0,
			isPageHeight: false,

			sourceDoc: [],
		};
	}

	componentDidMount() {
		const { location: { query } } = this.props;
		if (query.id) {
			this.info(query.id);
		};
		timer = setTimeout(() => {
			this.getPageHeight()
		}, 500)
		window.addEventListener('resize', this.getPageHeight)
	}

	componentWillUnmount() {
		timer && clearTimeout(timer);
		window.removeEventListener('resize', this.getPageHeight)
	}

	getPageHeight = () => {
		if (document.getElementById('color_tag_file')) {
			console.log(document.getElementById('color_tag_file').clientHeight);
			this.setState({ pageHeight: document.getElementById('color_tag_file').clientHeight - 76 })
		}
	}

	info = async id => {
		let res = await getFileInfo({ id });
		if (res.code === 0) {
			let knowledgeTagList = [];
			if (res.data.tagTypeList && res.data.tagTypeList.length) {
				res.data.tagTypeList.forEach(item => {
					if (item.tagList && item.tagList.length > 0) {
						item.tagList.forEach(i => {
							knowledgeTagList.push({ color: item.tagColor, id: i.id, name: i.tagValue })
						})
					}
				});
			};
			this.setState({
				title: res.data.docName,
				knowledgeTagList,
				// fileTitle: res.data.docContent.match(/\n(?:[^\n])*/g)[0].replace(/\n/gi, ''),
				// content: res.data.docContent.slice(this.getStrHtml(res.data.docContent).length, -1),
				fileTitle: res.data.docTitle,
				content: res.data.docContent,
				sourceDoc: res.data.sourceFile ? [res.data.sourceFile] : [],
			})
		}
	}

	getStr(str) {
		return str.match(/\n(?:[^\n])*/g, function (s) {
			return s;
		})
	}

	getStrHtml = (str) => {
		var v = (this.getStr(str)[0].replace(/\n(([\w])+)?n/g, function ($1, $2) {
			return $2;
		}).split(" "))[0];

		return this.getStr(str)[0] + "/n"
	}

	backRouter = () => {
		this.getKnowledgeFileList();
	}

	setTitle = e => {
		this.setState({ title: e.target.value })
	}

	save = () => {
		const { match: { params: { id }, }, route, location: { params, query } } = this.props;
		const { title, content, fileTitle, knowledgeTagList, sourceDoc } = this.state;
		if (!title || title == '') {
			return message.error(formatMessage({ id: 'editFile.addMarkdown.enterFileName' }))
		};
		if (!fileTitle || fileTitle === '') {
			return message.error(formatMessage({ id: 'editFile.addMarkdown.enterFileTitle' }))
		};
		if (!content || content === '' || content == '\n') {
			return message.error(formatMessage({ id: 'editFile.addMarkdown.enterFileContent' }))
		};
		let obj = {
			libraryId: id,
			categoryId: query.fileCategoryId,
			categoryPath: query.fileCategoryPath,
			docName: title,
			docTitle: fileTitle,
			docContent: content,
			knowledgeTagList: knowledgeTagList.map(i => i.id),
		};
		if (sourceDoc && sourceDoc.length > 0) {
			obj.sourceFileId = sourceDoc[0].id;
		};
		this.setState({ btnLoading: true }, async () => {
			if (query.id) {
				obj.id = query.id;
				let res = await editFile(obj);
				// console.log(res);
				if (res.code == 0) {
					message.info(res.msg);
					this.setState({ btnLoading: false });
				} else {
					this.setState({ btnLoading: false });
				}
			} else {
				let res = await addFile(obj);
				// console.log(res);
				if (res.code == 0) {
					message.info(res.msg);
					this.getKnowledgeFileList();
					this.setState({ btnLoading: false });
				} else {
					this.setState({ btnLoading: false });
				}
			}
		})
	}

	// 新增自定义文档
	getKnowledgeFileList = () => {
		const { match: { params: { id }, }, location: { query,pathname }, dispatch } = this.props;
		let url = pathname.indexOf("publicResource") != -1 ? "/publicResource/documentLibrary/" + id + "/file" : "/documentLibrary/" + id + "/file";
		dispatch(routerRedux.push({ pathname:url, query: { fileCategoryId: query.fileCategoryId } }));
	}

	render() {
		const { match: { params: { id }, }, route, location: { params, query } } = this.props;
		const { isShowTitle, title, btnLoading, knowledgeTagList, relatedTagVisible, pageHeight, isPageHeight, sourceDoc } = this.state;
		const optionDisabled = query.optionDisabled == 'true' || query.optionDisabled == true ? true : false;    

		return (
			<Card bordered={false}>
				<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '-8px 0 12px' }}>
					<div style={{ fontWeight: 'bold', fontSize: '15px' }}>
						{query.id ? (
							isShowTitle ? (
								<Input placeholder={formatMessage({ id: 'editFile.addMarkdown.placeholder.docName' })} value={title} onChange={e => this.setTitle(e)} />
							) : (
								<>
									<span>{title}</span>
									<Icon type="edit" style={{ marginLeft: 6 }} onClick={() => this.setState({ isShowTitle: true })} />
								</>
							)
						) : (
							<Input placeholder={formatMessage({ id: 'editFile.addMarkdown.placeholder.docName' })} value={title} onChange={e => this.setTitle(e)} />
						)}
					</div>
					<div>
						<Upload
							name='file'
							listType='picture'
							showUploadList={false}
							beforeUpload={this.beforeUploadFile}
							onChange={this.handleChange}
							accept=".txt,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.md"
							disabled={optionDisabled}
						>
							<Button style={{ marginRight: 10 }} type="primary" disabled={optionDisabled}>
								{formatMessage({ id: 'editFile.common.uploadSourceDoc' })}
							</Button>
						</Upload>
						<Button type="primary" style={{ marginRight: 10 }} onClick={this.save} loading={btnLoading} disabled={optionDisabled}>
							{formatMessage({ id: 'editFile.common.save' })}
						</Button>
						<Button onClick={this.backRouter} icon="arrow-left">
							{formatMessage({ id: 'editFile.common.back' })}
						</Button>
					</div>
				</div>
				{knowledgeTagList && knowledgeTagList.length > 0 ? (
					<div style={{ marginBottom: 20, display: 'flex', position: 'relative' }}>
						<div style={{ maxHeight: isPageHeight ? 'unset' : '76px', overflow: 'hidden', flex: 1 }}>
							<span id="color_tag_file" style={{ display: 'flex', flexFlow: 'wrap', gap: '12px', }}>
								<span style={{ lineHeight: '32px', fontWeight: 'bold', fontSize: '14px' }}>
									{formatMessage({ id: 'editFile.addMarkdown.relatedTags' })}
								</span>
								{knowledgeTagList.map((item, index) => {
									return (
										<>
											{item.color == '#FFF' || item.color == '#FFFFFF' || item.color == '' ? (
												<Tag
													key={index}
													color={item.color}
													style={{
														padding: '5px 12px',
														fontSize: '14px',
														margin: 0,
														color: item.color + '99',
														background: item.color + '1A',
														// border: '1px solid '+ item.color,
													}}
												>
													<span>{item.name}</span>
													<Icon type="close" style={{ color: item.color + '99', marginLeft: 8, }} onClick={() => this.removeRelatedTagData(item)} />
												</Tag>
											) : (
												<Tag
													key={index}
													color={item.color}
													style={{
														padding: '5px 12px',
														fontSize: '14px',
														margin: 0,
														color: item.color + '99',
														background: item.color + '1A',
														// border: '1px solid '+ item.color,
													}}
												>
													<span>{item.name}</span>
													<Icon type="close" style={{ color: item.color + '99', marginLeft: 8 }} onClick={() => this.removeRelatedTagData(item)} />
												</Tag>
											)}
										</>
									)
								})}
							</span>
						</div>
						{pageHeight && pageHeight > 0 ? (
							<div style={{ width: '60px' }}>
								<Button
									type="link"
									style={{ position: 'absolute', bottom: '0px', right: '0px', }}
									onClick={() => this.setState({ isPageHeight: !isPageHeight })}
								>
									{isPageHeight ? '收起' : '全部'}
								</Button>
							</div>
						) : null}
					</div>
				) : null}
				{sourceDoc && sourceDoc.length > 0 ? (
					<div style={{ fontSize: '16px', marginBottom: 12 }}>
						<span>{formatMessage({ id: 'editFile.addMarkdown.sourceDoc' })}</span>
						<span>{sourceDoc[0].name}</span>
					</div>
				) : null}
				<MarkdownEditor
					value={this.state.content}
					title={this.state.fileTitle}
					name='markdown-editor'
					id='markdown-editor'
					height='calc(100vh - 245px)'
					width='700'
					onChange={(value, type) => {
						switch (type) {
							case 'content':
								this.setState({ content: value });
								break;
							case 'title':
								this.setState({ fileTitle: value });
								break;
						}
					}}
					ref={(r) => (this.vEditor = r)}
				/>
				<RelatedKnowledgeTag
					visible={relatedTagVisible}
					onClose={this.closeRelatedTagModal}
					getRelatedList={this.getRelatedTagList}
					onRef={(ref) => (this.RelatedKnowledgeTag = ref)}
				/>
			</Card>
		);
	}


	/**
	 * 关联知识标签
	 * @param data
	 * @returns {*}
	 */
	openRelatedKnowledgeTagModal = () => {
		let { knowledgeTagList } = this.state;
		this.RelatedKnowledgeTag.getList(knowledgeTagList);
		this.setState({ relatedTagVisible: true, });
	};

	closeRelatedTagModal = () => {
		this.setState({ relatedTagVisible: false, });
	};

	getRelatedTagList = (data) => {
		this.setState({ knowledgeTagList: data, });
	};

	removeRelatedTagData = (tag) => {
		let { knowledgeTagList } = this.state;
		const newData = knowledgeTagList.filter(item => item != tag);
		this.setState({ knowledgeTagList: newData });
	};


	/**
	 * 
	 * @param {'上传源文档'} fileName 
	 * @returns 
	 */
	getFileNameType = fileName => {
		let type = fileName ? fileName.split('.') ? fileName.split('.').length > 1 ? fileName.split('.')[fileName.split('.').length-1] : null : null : null;
		return type;
	}

	beforeUploadFile = (file) => {
		console.log(file);
		if (file.size / 1024 / 1024 > 25) {
			message.error(formatMessage({ id: 'editFile.addMarkdown.uploadSizeLimit' }));
			return false;
		} else if (
			this.getFileNameType(file.name).toLowerCase() !== 'txt' &&
			this.getFileNameType(file.name).toLowerCase() !== 'pdf' &&
			this.getFileNameType(file.name).toLowerCase() !== 'doc' &&
			this.getFileNameType(file.name).toLowerCase() !== 'docx' &&
			this.getFileNameType(file.name).toLowerCase() !== 'xls' &&
			this.getFileNameType(file.name).toLowerCase() !== 'xlsx' &&
			this.getFileNameType(file.name).toLowerCase() !== 'ppt' &&
			this.getFileNameType(file.name).toLowerCase() !== 'pptx' &&
			this.getFileNameType(file.name).toLowerCase() !== 'md'
		) {
			message.error(formatMessage({ id: 'editFile.addMarkdown.fileTypeLimit' }))
			return false;
		} else {
			this.uploadFile(file);
			return false;
		}
	}

	uploadFile = async (file) => {
		let _this = this;
		const formData = new FormData();
		formData.append('files', file);
		let res = await docUploadAttach(formData);
		// console.log('==========>>>>>>>>>>>>>>>>>>>>>>>', res);
		if (res.code === 0) {
			this.setState({ sourceDoc: res.data })
		};
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(AddMarkdown);